package com.chong.volleydemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * *Volley GET/POST请求的基本步骤：
 * 1. 创建一个RequestQueue对象。
 * 2. 创建一个 StringRequest/MyJsonObjectRequest/JsonArrayRequest 对象。
 * 3. 将 StringRequest/MyJsonObjectRequest/JsonArrayRequest 对象添加到RequestQueue里面。
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_resp1;
    private Button btn_get_string, btn_post_string, btn_get_jsonobject, btn_post_jsonobject, btn_post_jsonobject2, btn_get_jsonarray;
    private String urlget = "http://gc.ditu.aliyun.com/geocoding?a=苏州市";
    private String urlpost = "http://api.24ht.net/app/signin";
    private String urlpost1 = "http://114.215.47.93:80/zhuhai/httpServer?content=150000";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setEvent();
    }

    private void initView() {
        tv_resp1 = (TextView) findViewById(R.id.tv_resp1);
        btn_get_string = (Button) findViewById(R.id.btn_get_string);
        btn_post_string = (Button) findViewById(R.id.btn_post_string);
        btn_get_jsonobject = (Button) findViewById(R.id.btn_get_jsonobject);
        btn_post_jsonobject = (Button) findViewById(R.id.btn_post_jsonobject);
        btn_post_jsonobject2 = (Button) findViewById(R.id.btn_post_jsonobject2);
        btn_get_jsonarray = (Button) findViewById(R.id.btn_get_jsonarray);
    }

    private void setEvent() {
        btn_get_string.setOnClickListener(this);
        btn_post_string.setOnClickListener(this);
        btn_get_jsonobject.setOnClickListener(this);
        btn_post_jsonobject.setOnClickListener(this);
        btn_post_jsonobject2.setOnClickListener(this);
        btn_get_jsonarray.setOnClickListener(this);
    }
//
//    private Handler handler=new Handler(){
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case 1:
//                    String text=(String) msg.obj;
//                    tv_resp1.setText(text);
//
//                    break;
//
//                default:
//                    break;
//            }
//        }
//
//    };


//                    String url1 = "http://114.215.47.93:80/zhuhai/httpServer?content=150000";
//                    Map<String, String> map = new HashMap<>();
//                    JSONObject object = new JSONObject();
//                    map.put("name","内蒙一大队11");
//                    map.put("jingd","113.21121");
//                    map.put("weid","23.12111");
//                    map.put("shangbr","北京四环路1");




    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_get_string:
                volley_StringRequestGet();
                break;
            case R.id.btn_post_string:
                volley_StringRequestGetPost();
                break;
            case R.id.btn_get_jsonobject:
                volley_JsonObjectRequestGet();
                break;
            case R.id.btn_post_jsonobject:
                volley_JsonObjectRequestPost();
                break;
            case R.id.btn_post_jsonobject2:
                volley_JsonObjectRequestPost2();
                break;
            case R.id.btn_get_jsonarray:
                volley_JsonArrayRequestGet();
                break;
        }
    }

    /*
     * StringRequest
     * StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
     * 这个类可以用来从服务器获取String，如果想自己解析请求响应可以使用这个类，例如返回xml数据。它还可以使用重载的构造函数定制请求.
     *
     * GET方式请求服务器
     */
    private void volley_StringRequestGet() {
        StringRequest request = new StringRequest(Request.Method.GET, urlget, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                tv_resp1.setText(response);
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                tv_resp1.setText(error.toString());
            }
        });

        request.setTag("volley_StringRequestGet");
        MyApplication.getInstance().addToRequestQueue(request);
    }

    /*
     * StringRequest
     * StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)
     * 这个类可以用来从服务器获取String，如果想自己解析请求响应可以使用这个类，例如返回xml数据。它还可以使用重载的构造函数定制请求.
     *
     * POST方式请求服务器
     */
    private void volley_StringRequestGetPost() {
        StringRequest request = new StringRequest(Request.Method.POST, urlpost, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                tv_resp1.setText(response);
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                tv_resp1.setText(error.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("user", "jt1024");
                map.put("psw", "111111");
                return map;
            }
        };

        request.setTag("volley_StringRequestGetPost");
        MyApplication.getInstance().addToRequestQueue(request);
    }

    /*
     * MyJsonObjectRequest
     * MyJsonObjectRequest — To send and receive JSON Object from the Server
     * 这个类可以用来发送和接收JSON对象。
     * 这个类的一个重载构造函数允许设置适当的请求方法（DELETE，GET，POST和PUT）。
     *
     * GET方式请求服务器
     */
    private void volley_JsonObjectRequestGet() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlget, null, new Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                tv_resp1.setText(response.toString());
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                tv_resp1.setText(error.toString());
            }
        });

        request.setTag("volley_JsonObjectRequestGet");
        MyApplication.getInstance().addToRequestQueue(request);
    }

    /*
     * MyJsonObjectRequest
     * MyJsonObjectRequest — To send and receive JSON Object from the Server
     * 这个类可以用来发送和接收JSON对象。
     * 这个类的一个重载构造函数允许设置适当的请求方法（DELETE，GET，POST和PUT）。
     *
     * POST方式请求服务器
     */
    private void volley_JsonObjectRequestPost() {
//        Map<String, String> map = new HashMap<String, String>();
//        map.put("user", "jt1024");
//        map.put("psw", "111111");
//        JSONObject object = new JSONObject(map);

        String url = "http://114.215.47.93:80/zhuhai/httpServer?content=150000";

        Map<String, String> map = new HashMap<>();

        map.put("name","内蒙一大队11");
        map.put("jingd","113.21121");
        map.put("weid","23.12111");
        map.put("shangbr","北京四环路1");
        JSONObject object = new JSONObject(map);
        JSONArray array = new JSONArray();
        array.put(object);

//        MyJsonObjectRequest request = new MyJsonObjectRequest(Method.POST, url, array, new Response.Listener<JSONObject>() {
//            @Override
//            public void onResponse(JSONObject response) {
//                tv_resp1.setText(response.toString());
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                tv_resp1.setText(error.toString());
//            }
//        });


        MyXMLRequest request = new MyXMLRequest(Method.POST, url, array, new Listener<XmlPullParser>() {
            @Override
            public void onResponse(XmlPullParser response) {
                try {
                    int eventType = response.getEventType();
                    while (eventType != XmlPullParser.END_DOCUMENT) {
                        String nodeName = response.getName(); //节点名称
                        switch (eventType) {
                            case XmlPullParser.START_DOCUMENT: //文档开始
                                Log.i("CC","=====START_DOCUMENT===response.getName()==="+nodeName);
                                break;
                            case XmlPullParser.START_TAG:// 开始标签
                                Log.i("CC","=====START_TAG====response.getName()=="+nodeName);

                               if("status".equals(nodeName)){
                                    boolean b = Boolean.valueOf(response.nextText());  // 解析为true,上传成功
                                    Toast.makeText(getApplicationContext(),"response======="+b,Toast.LENGTH_LONG).show();
                               }

                                break;
                            case XmlPullParser.END_TAG:// 标签结束
                                Log.i("CC","=====END_TAG===response.getName()==="+nodeName);

                                break;
                        }
                        eventType = response.next();
                    }
                } catch (XmlPullParserException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        request.setTag("volley_JsonObjectRequestPost");
        MyApplication.getInstance().addToRequestQueue(request);
    }

    /*
     * MyJsonObjectRequest
     * 如果服务端并不支持json的请求方式,比如常见的spring mvc服务端,就很难支持json的请求方式,
     * 那么就需要客户端以普通的post方式进行提交,服务端返回json串
     * 首先在Activity类里,继承Request实现一个NormalPostRequest类
     *
     * 服务端不支持json的请求方式
     */
    private void volley_JsonObjectRequestPost2() {
        String url = "http://api.24ht.net/app/signin";
        Map<String, String> map = new HashMap<String, String>();
        map.put("user", "jt1024");
        map.put("psw", "111111");
        JSONObject object = new JSONObject(map);


        NormalPostRequest request = new NormalPostRequest(url, map, new Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                tv_resp1.setText(response.toString());
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                tv_resp1.setText(error.toString());
            }
        });
        request.setTag("volley_JsonObjectRequestPost2");
        MyApplication.getInstance().addToRequestQueue(request);
    }

    private void volley_JsonArrayRequestGet() {
        JsonArrayRequest request = new JsonArrayRequest(urlget, new Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                tv_resp1.setText(response.toString());
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                tv_resp1.setText(error.toString());
            }
        });

        request.setTag("volley_JsonArrayRequestGet");
        MyApplication.getInstance().addToRequestQueue(request);
    }
}
